{
 "metadata": {
  "signature": "sha256:4549bb8fefd2c03a112ebbf7629b5335ae07972cd1a2749ca391670829fc3a9d"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "id": "6D0B6272BFB14E8D8D282A605EA1565B",
     "metadata": {},
     "source": [
      "1 \u6295\u8d44\u8005\u504f\u597d\n",
      "\u9a6c\u79d1\u7ef4\u8328\u5747\u503c\u65b9\u5dee\u6a21\u578b\u6700\u65e9\u63d0\u51fa\u5c06\u6570\u7406\u7edf\u8ba1\u7684\u65b9\u6cd5\u5e94\u7528\u5230\u6295\u8d44\u7ec4\u5408\u9009\u62e9\u4e0a\uff0c\u5e76\u5c06\u8d44\u4ea7\u7684\u671f\u671b\u6536\u76ca\u7387\u7684\u6ce2\u52a8\u7387\u5b9a\u4e49\u4e3a\u98ce\u9669\u3002\u8fd9\u79cd\u5b9a\u4e49\u4e0b\uff0c\u6211\u4eec\u4f7f\u7528\u6536\u76ca\u7387\u7684\u5747\u503c\uff08E(r)\uff09\u548c\u6807\u51c6\u5dee\uff08\u03c3(r)\uff09\u6765\u523b\u753b \u201c\u6536\u76ca\u201d\u548c\u201c\u98ce\u9669\u201d\u3002\n",
      "\u901a\u5e38\uff0c\u6211\u4eec\u8ba4\u4e3a\u4eba\u4eec\u662f\u201c\u98ce\u9669\u538c\u6076\u201d\u7684\uff0c\u5e76\u6784\u9020\u5982\u4e0b\u5f62\u5f0f\u7684\u6548\u7528\u51fd\u6570\u6765\u4ee3\u8868\u6295\u8d44\u8005\u7684\u6295\u8d44\u504f\u597d\uff1a\n",
      "U(r)=E(r)-  1/2 A\u03c3^2 (r)\n",
      "\u5176\u4e2dE(r)\u8868\u793a\u6295\u8d44\u7ec4\u5408\u7684\u9884\u671f\u6536\u76ca\u7387\uff0c\u03c3^2 (r)\u8868\u793a\u6295\u8d44\u7ec4\u5408\u7684\u65b9\u5dee\uff1b\u9884\u671f\u6536\u76ca\u7387\u8d8a\u9ad8\uff0c\u6548\u7528\u503c\u8d8a\u9ad8\uff0c\u6536\u76ca\u65b9\u5dee\u8d8a\u5927\uff0c\u6548\u7528\u503c\u8d8a\u5c0f\u3002\u8fd9\u8868\u660e\u6295\u8d44\u8005\u559c\u6b22\u66f4\u9ad8\u7684E(r)\uff0c\u800c\u4e0d\u559c\u6b22\u9ad8\u7684\u03c3^2 (r)\u3002\u7531\u4e8e\u4e0d\u540c\u7684\u6295\u8d44\u8005\u5bf9\u4e8e\u98ce\u9669\u548c\u6536\u76ca\u6709\u4e0d\u540c\u7684\u504f\u597d\uff0c\u56e0\u6b64\u6548\u7528\u51fd\u6570\u4e2d\u52a0\u5165\u98ce\u9669\u538c\u6076\u7cfb\u6570\u53c2\u6570A\u8868\u793a\u6295\u8d44\u8005\u4e0d\u540c\u504f\u597d\uff0cA\u8d8a\u5927\uff0c\u5219\u6295\u8d44\u8005\u4e3a\u8ffd\u6c42\u66f4\u9ad8\u7684\u6536\u76ca\u613f\u610f\u627f\u62c5\u66f4\u5c0f\u7684\u98ce\u9669\uff0c\u6216\u8005\u8bf4\u8be5\u6295\u8d44\u8005\u8981\u6c42\u66f4\u9ad8\u7684\u6536\u76ca\u8865\u507f\u9762\u4e34\u7684\u98ce\u9669\u3002\n",
      "\u4e0b\u9762\u7684\u4e00\u6bb5\u4ee3\u7801\u6784\u9020\u4e86\u4e0d\u540c\u7684A\u5bf9\u4e8e\u6295\u8d44\u8005\u6548\u7528\u7684\u5f71\u54cd\uff0c\u4ece\u8f93\u51fa\u7684\u56fe\u5f62\u4e2d\u53ef\u4ee5\u770b\u51fa\uff0cA\u8d8a\u5927\u6295\u8d44\u8005\u76f8\u540c\u6548\u7528\u503c\u7684\u65e0\u5dee\u5f02\u66f2\u7ebf\u8d8a\u9661\u5ced\uff0c\u6295\u8d44\u8005\u4e3a\u627f\u62c5\u98ce\u9669\u8981\u6c42\u7684\u6536\u76ca\u8865\u507f\u8d8a\u5927\u3002\n"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "E176B12BFFBC44DD972FBE4509DD4F40",
     "input": [
      "import seaborn\n",
      "import numpy as np\n",
      "import matplotlib.pylab as pl\n",
      "\n",
      "U = 0.3\n",
      "sigmas = np.linspace(0., 1., 101)\n",
      "As = [0., 1., 2., 3.]\n",
      "indifference_curves = []\n",
      "for A in As:\n",
      "    Es = [U + 0.5 * A * sig*sig for sig in sigmas]\n",
      "    indifference_curves.append(Es)\n",
      "\n",
      "fig = pl.figure(figsize=(9, 6))\n",
      "plots = []\n",
      "for i, Es in enumerate(indifference_curves):\n",
      "    plots.append(pl.plot(sigmas, Es, label=\"A = {}\".format(As[i])))\n",
      "pl.title(\"Indifference Curve with U = {}\".format(U))\n",
      "pl.xlabel(\"$\\sigma(r)$\")\n",
      "pl.ylabel(\"$E(r)$\")\n",
      "pl.legend(loc='best')\n",
      "pl.show()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "id": "F543FB3B1D2C4BC18E60B6AD01615EC2",
     "metadata": {},
     "source": [
      "U\u540c\u65f6\u662fE\u548c\u03c3\u7684\u51fd\u6570\uff0c\u6240\u4ee5\u5728\u03c3-E\u56fe\u4e0a\uff0c\u5bf9\u4e8e\u786e\u5b9a\u7684A\uff0c\u4e0d\u540c\u7684U\u8868\u73b0\u4e3a\u4e00\u7ec4\u4e0d\u76f8\u4ea4\u7684\u629b\u7269\u7ebf\uff0c\u8fd9\u5c31\u662f\u6548\u7528\u7684\u65e0\u5dee\u5f02\u66f2\u7ebf\uff0c\u8d8a\u5f80\u5de6\u4e0a\u65b9\u7684\u65e0\u5dee\u5f02\u66f2\u7ebf\uff0c\u4ee3\u8868\u8d8a\u9ad8\u7684\u6548\u7528\uff0c\u56e0\u6b64\u6295\u8d44\u8005\u603b\u662f\u504f\u597d\u4f4d\u4e8e\u5de6\u4e0a\u65b9\u7684\u65e0\u5dee\u5f02\u66f2\u7ebf\u4e0a\u9762\u7684\u6295\u8d44\u7ec4\u5408\u3002\u4e0b\u9762\u4e00\u6bb5\u4ee3\u7801\u7ed8\u5236\u51fa\u4e86A = 2\u65f6\u7684\u4e00\u7ec4\u65e0\u5dee\u5f02\u66f2\u7ebf\u3002"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "E997BCA68CE94646BC28A54E3D9AD371",
     "input": [
      "import seaborn\n",
      "import numpy as np\n",
      "import matplotlib.pylab as pl\n",
      "\n",
      "A = 2.\n",
      "sigmas = np.linspace(0., 1., 101)\n",
      "Us = [0.05, 0.1, 0.15, 0.2]\n",
      "indifference_curves = []\n",
      "for U in Us:\n",
      "    Es = [U + 0.5 * A * sig*sig for sig in sigmas]\n",
      "    indifference_curves.append(Es)\n",
      "\n",
      "fig = pl.figure(figsize=(9, 6))\n",
      "plots = []\n",
      "for i, Es in enumerate(indifference_curves):\n",
      "    plots.append(pl.plot(sigmas, Es, label=\"U = {}\".format(Us[i])))\n",
      "pl.title(\"Indifference Curve with A = {}\".format(A))\n",
      "pl.xlabel(\"$\\sigma(r)$\")\n",
      "pl.ylabel(\"$E(r)$\")\n",
      "pl.legend(loc='best')\n",
      "pl.show()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "id": "836BBF7AA01842478499A33FCB36AB9A",
     "metadata": {},
     "source": [
      "2 \u8d44\u4ea7\u7ec4\u5408\n",
      "\u5047\u8bbe\u6709\u4e24\u79cd\u8d44\u4ea7E_1\u548cE_2\uff0c\u5176\u9884\u671f\u6536\u76ca\u7387\u548c\u65b9\u5dee\u5206\u522b\u4e3ar_1\u3001\u03c3_1^2\u548cr_2\u3001\u03c3_2^2,\u6536\u76ca\u7387\u76f8\u5173\u7cfb\u6570\u4e3a\u03c1\u3002\u53e6\u6709\uff0cr_1<r_2\u3001\u30160<\u03c3\u3017_1<\u03c3_2\u3002\u5982\u679c\u540c\u65f6\u6295\u8d44\u4e8e\u4e24\u79cd\u8d44\u4ea7\uff0c\u6743\u91cd\u5206\u522b\u4e3aw_1\u30011-w_1\uff0c\u5219\u7ec4\u5408\u7684\u671f\u671b\u6536\u76ca\u7387\u548c\u65b9\u5dee\u53ef\u8868\u793a\u4e3a\uff1a\n",
      "r=w_1 r_1+(1-w_1)r_2\n",
      "\u03c3^2= w_1^2 \u03c3_1^2+\u3016(1-w_1)\u3017^2 \u03c3_2^2+2w_1 (1-w_1)\u03c1\u03c3_1 \u03c3_2\n",
      "\u5bb9\u6613\u8bc1\u660e,\u5f53\u4e14\u4ec5\u5f53\u03c1=1\u65f6\u8d44\u4ea7\u7ec4\u5408\u6807\u51c6\u5dee\u4e0e\u9884\u671f\u6536\u76ca\u5448\u7ebf\u6027\u5173\u7cfb\u3002\u7531\u4e8e\u03c1\u7684\u53d6\u503c\u8303\u56f4\u5728-1\u548c1\u4e4b\u95f4\uff0c\u56e0\u6b64\u901a\u5e38\u60c5\u51b5\u4e0b\u03c3^2= w_1^2 \u03c3_1^2+\u3016(1-w_1)\u3017^2 \u03c3_1^2+2w_1 (1-w_1 )\u03c1\u03c3_1 \u03c3_2<\u3016(w_1 \u03c3_1+(1-w_1 )\u03c3_2)\u3017^2\uff0c\u5373\u7ec4\u5408\u6807\u51c6\u5dee\u5c0f\u4e8e\u4e24\u79cd\u8d44\u4ea7\u6807\u51c6\u5dee\u7684\u52a0\u6743\u5e73\u5747\uff0c\u6536\u76ca-\u6807\u51c6\u5dee\u70b9\u5728\u4e24\u79cd\u8d44\u4ea7\u6536\u76ca-\u6807\u51c6\u5dee\u70b9\u8fde\u7ebf\u7684\u5de6\u4fa7\u3002\u751a\u81f3\u5728\u5927\u591a\u6570\u60c5\u51b5\u4e0b\uff0c\u5f53\u628a\u6ce2\u52a8\u7387\u66f4\u5927\u7684\u8d44\u4ea72\u5f00\u59cb\u5f15\u5165\u7ec4\u5408\u65f6\uff0c\u5176\u6536\u76ca\u6ce2\u52a8\u751a\u81f3\u6bd4\u53ea\u6295\u8d44\u4e8e\u8d44\u4ea71\u65f6\u66f4\u5c0f\uff0c\u5f53\u7ecf\u8fc7\u6700\u5c0f\u65b9\u5dee\u4e34\u754c\u70b9\u65f6\u624d\u4f1a\u6162\u6162\u589e\u5927\u3002\u8fd9\u4e5f\u4f53\u73b0\u4e86\u6295\u8d44\u7ec4\u5408\u7684\u91cd\u8981\u6027\u2014\u2014\u901a\u8fc7\u5206\u6563\u6295\u8d44\u4ee5\u66f4\u5c0f\u7684\u7ec4\u5408\u98ce\u9669\u83b7\u5f97\u66f4\u9ad8\u7684\u6536\u76ca\u3002\u5982\u4e0b\u4ee3\u7801\u663e\u793a\u4e86\u5f53\u6295\u8d44\u4ea7\u54c1\u53ea\u6709\u4e24\u79cd\u65f6\uff0c\u4e0d\u540c\u76f8\u5173\u7cfb\u6570\u5bf9\u5e94\u7684\u4e0d\u540c\u6709\u6548\u8fb9\u754c\u3002"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "79DB3698FF994E3F833C5AB91C397BEE",
     "input": [
      "import seaborn\n",
      "import numpy as np\n",
      "import matplotlib.pylab as pl\n",
      "\n",
      "phos = [-1, -0.5, 0, 0.5, 1]\n",
      "r1, sigma1 = 0.05, 0.05\n",
      "r2, sigma2 = 0.10, 0.25\n",
      "\n",
      "rs = [r1*t + r2*(1-t) for t in np.linspace(0., 1., 101)]\n",
      "all_sigmas = []\n",
      "for pho in phos:\n",
      "    all_sigmas.append(np.sqrt([t*t*sigma1*sigma1 + (1-t)*(1-t)*sigma2*sigma2 + 2*pho*t*(1-t)*sigma1*sigma2 for t in np.linspace(0., 1., 101)]))\n",
      "\n",
      "fig = pl.figure(figsize=(9, 6))\n",
      "plots = []\n",
      "for i, sigmas in enumerate(all_sigmas):\n",
      "    plots.append(pl.plot(sigmas, rs, label=\"pho = {}\".format(phos[i])))\n",
      "pl.title(\"Convex Combinations of Two Risky Assets\")\n",
      "pl.xlabel(\"$\\sigma(r)$\")\n",
      "pl.ylabel(\"$E(r)$\")\n",
      "pl.legend(loc='best')\n",
      "pl.show()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "id": "D0EC2FC49E9E4A698A8F90B91F0A6665",
     "metadata": {},
     "source": [
      "3 \u6709\u6548\u8fb9\u754c\u548c\u6295\u8d44\u7ec4\u5408\u9009\u62e9\n",
      "\u5f53\u6295\u8d44\u8005\u9762\u4e34\u7684\u53ef\u9009\u8d44\u4ea7\u5927\u4e8e2\u79cd\u65f6\uff0c\u6807\u51c6\u5dee\u548c\u6536\u76ca\u7684\u5173\u7cfb\u5c31\u4e0d\u4ec5\u4ec5\u5c40\u9650\u4e8e\u4e00\u6761\u66f2\u7ebf\u4e86\uff0c\u901a\u8fc7\u6743\u91cd\u7684\u9009\u53d6\uff0c\u6295\u8d44\u8005\u53ef\u9009\u7684\u6536\u76ca-\u6807\u51c6\u5dee\u70b9\u6784\u6210\u4e00\u4e2a\u6709\u8fb9\u754c\u7684\u9762\u3002\u4eba\u4eec\u8d8b\u5229\u907f\u9669\u7684\u5fc3\u7406\u51b3\u5b9a\u4e86\u7406\u6027\u6295\u8d44\u4eba\u5728\u9762\u4e34\u540c\u6837\u98ce\u9669\u65f6\uff0c\u4f1a\u9009\u62e9\u9884\u671f\u6536\u76ca\u7387\u66f4\u9ad8\u7684\u7ec4\u5408\uff1b\u800c\u5728\u9884\u671f\u6536\u76ca\u76f8\u540c\u65f6\uff0c\u4f1a\u9009\u62e9\u98ce\u9669\u8f83\u4f4e\u7684\u7ec4\u5408\u3002\u5728\u6240\u6709\u53ef\u9009\u7684\u9884\u671f\u6536\u76ca-\u6807\u51c6\u5dee\u70b9\u4e2d\uff0c\u4f4d\u4e8e\u6700\u5de6\u4fa7\u7684\u90e8\u5206\u6784\u6210\u4e86\u4e00\u6761\u8fb9\u754c\u7ebf\uff0c\u5176\u4e2d\u4ece\u6700\u5c0f\u65b9\u5dee\u70b9\u5f80\u4e0a\u7684\u90e8\u5206\u6784\u6210\u4e86\u6709\u6548\u8fb9\u754c\u3002\u5728\u8be5\u8fb9\u754c\u7ebf\u53f3\u4e0b\u65b9\u7684\u6240\u6709\u70b9\u662f\u65e0\u6548\u7684\u6295\u8d44\u7ec4\u5408\uff0c\u6ca1\u6709\u4eba\u4f1a\u9009\u62e9\uff1b\u5728\u8be5\u8fb9\u754c\u7ebf\u5750\u4e0a\u7684\u6240\u6709\u70b9\u662f\u4e0d\u53ef\u80fd\u8fbe\u5230\u7684\u6295\u8d44\u7ec4\u5408\u3002\n",
      "\u5982\u4e0b\u7684\u4ee3\u7801\u4e2d\uff0c\u6211\u4eec\u7ed9\u51fa\u4e86\u5229\u7528\u901a\u8054\u6570\u636e\u6784\u9020\u6295\u8d44\u7ec4\u5408\uff0c\u5e76\u83b7\u53d6\u6709\u6548\u8fb9\u754c\u4e0a\u51e0\u4e2a\u7279\u6b8a\u70b9\u7684\u51fd\u6570\uff0c\u4ee5\u53ca\u76f8\u5173\u7684\u8c03\u7528\u793a\u4f8b\u3002\u5176\u4e2d\uff0cget_efficient_frontier()\u51fd\u6570\u7528\u4e8e\u83b7\u53d6\u6709\u6548\u8fb9\u754c\uff1bdraw_efficient_frontier()\u51fd\u6570\u7528\u4e8e\u7ed8\u5236\u6709\u6548\u8fb9\u754c\u56fe\u5f62\uff1bget_minimum_variance_portfolio()\u51fd\u6570\u7528\u4e8e\u6c42\u89e3\u6700\u5c0f\u65b9\u5dee\u7ec4\u5408\u70b9\uff1b get_maximum_utility_portfolio()\u51fd\u6570\u7528\u4e8e\u6c42\u89e3\u7ed9\u5b9a\u6548\u7528\u51fd\u6570\u7684\u6548\u7528\u6700\u5927\u5316\u70b9\uff1bget_maximum_sharpe_portfolio()\u51fd\u6570\u7528\u4e8e\u5bfb\u627e\u6700\u5927\u590f\u666e\u7387\u70b9\u3002"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "5BB9AE2E29B7457AA780EE5A7896E2B5",
     "input": [
      "def describe(return_table, is_print=True):\n",
      "    \"\"\"\n",
      "    \u8f93\u51fa\u6536\u76ca\u7387\u77e9\u9635\u7684\u63cf\u8ff0\u6027\u7edf\u8ba1\u91cf\uff0c\u5305\u62ec\uff1a\n",
      "        \u5e74\u5316\u6536\u76ca\u7387\n",
      "        \u5e74\u5316\u6807\u51c6\u5dee\n",
      "        \u76f8\u5173\u7cfb\u6570\u77e9\u9635\n",
      "    \n",
      "    Args:\n",
      "        return_table (DataFrame): \u6536\u76ca\u7387\u77e9\u9635\uff0c\u5217\u4e3a\u8d44\u4ea7\uff0c\u503c\u4e3a\u6309\u65e5\u671f\u5347\u5e8f\u6392\u5217\u7684\u6536\u76ca\u7387\n",
      "        is_print (bool): \u662f\u5426\u76f4\u63a5\u8f93\u51fa\n",
      "\n",
      "    Returns:\n",
      "        dict: \u63cf\u8ff0\u6027\u7edf\u8ba1\u91cf\u5b57\u5178\uff0c\u952e\u4e3a\"annualized_return\", \"annualized_volatility\", \"covariance_matrix\"\u548c\"coefficient_matrix\"\n",
      "\n",
      "    Examples:\n",
      "        >> describe(return_table)\n",
      "        >> describe(return_table, is_print=True)\n",
      "    \"\"\"\n",
      "    \n",
      "    import pandas as pd\n",
      "    from scipy.stats.mstats import gmean\n",
      "    \n",
      "    output = {}\n",
      "    output['annualized_return'] = pd.DataFrame(dict(zip(return_table.columns, gmean(return_table+1.)**252 - 1.)), index=[0], columns=return_table.columns)\n",
      "    output['annualized_volatility'] = pd.DataFrame(return_table.std() * np.sqrt(250)).T\n",
      "    output['covariance_matrix'] = return_table.cov() * 250.\n",
      "    output['coefficient_matrix'] = return_table.corr()\n",
      "        \n",
      "    if is_print:\n",
      "        for key, val in output.iteritems():\n",
      "            print \"{}:\\n{}\\n\".format(key, val)\n",
      "    \n",
      "    return output\n",
      "\n",
      "def get_efficient_frontier(return_table, allow_short=False, n_samples=25):\n",
      "    \"\"\"\n",
      "    \u8ba1\u7b97Efficient Frontier\n",
      "    \n",
      "    Args:\n",
      "        return_table (DataFrame): \u6536\u76ca\u7387\u77e9\u9635\uff0c\u5217\u4e3a\u8d44\u4ea7\uff0c\u503c\u4e3a\u6309\u65e5\u671f\u5347\u5e8f\u6392\u5217\u7684\u6536\u76ca\u7387\n",
      "        n_samples (int): \u7528\u4e8e\u8ba1\u7b97Efficient Frontier\u7684\u91c7\u6837\u70b9\u6570\u91cf\n",
      "\n",
      "    Returns:\n",
      "        DataFrame: Efficient Frontier\u7684\u7ed3\u679c\uff0c\u5217\u4e3a\"returns\", \"risks\", \"weights\"\n",
      "    \"\"\"\n",
      "    \n",
      "    import numpy as np\n",
      "    import pandas as pd\n",
      "    from cvxopt import matrix, solvers\n",
      "    \n",
      "    assets = return_table.columns\n",
      "    n_asset = len(assets)\n",
      "    if n_asset < 2:\n",
      "        raise ValueError(\"There must be at least 2 assets to calculate the efficient frontier!\")\n",
      "\n",
      "    output = describe(return_table, is_print=False)\n",
      "    covariance_matrix = matrix(output['covariance_matrix'].as_matrix())\n",
      "    expected_return = output['annualized_return'].iloc[0, :].as_matrix()\n",
      "\n",
      "    risks, returns, weights = [], [], []\n",
      "    for level_return in np.linspace(min(expected_return), max(expected_return), n_samples):\n",
      "        P = 2 * covariance_matrix\n",
      "        q = matrix(np.zeros(n_asset))\n",
      "        \n",
      "        if allow_short:\n",
      "            G = matrix(0., (n_asset, n_asset))\n",
      "        else:\n",
      "            G = matrix(np.diag(-1 * np.ones(n_asset)))\n",
      "        \n",
      "        h = matrix(0., (n_asset, 1))    \n",
      "        A = matrix(np.row_stack((np.ones(n_asset), expected_return)))\n",
      "        b = matrix([1.0, level_return])\n",
      "        solvers.options['show_progress'] = False\n",
      "        sol = solvers.qp(P, q, G, h, A, b)\n",
      "        risks.append(np.sqrt(sol['primal objective']))\n",
      "        returns.append(level_return)\n",
      "        weights.append(dict(zip(assets, list(sol['x'].T))))\n",
      "    \n",
      "    output = {\"returns\": returns,\n",
      "              \"risks\": risks,\n",
      "              \"weights\": weights}\n",
      "    output = pd.DataFrame(output)\n",
      "    return output\n",
      "\n",
      "def draw_efficient_frontier(effcient_frontier_output):\n",
      "    \"\"\"\n",
      "    \u7ed8\u51faEfficient Frontier\n",
      "    \n",
      "    Args:\n",
      "        effcient_frontier_output: Efficient Frontier\u7684\u8ba1\u7b97\u7ed3\u679c\uff0c\u5373get_efficient_frontier\u7684\u8f93\u51fa\n",
      "    \"\"\"\n",
      "\n",
      "    import seaborn\n",
      "    from matplotlib import pyplot as plt\n",
      "\n",
      "    fig = plt.figure(figsize=(7, 4))\n",
      "    ax = fig.add_subplot(111)\n",
      "    ax.plot(effcient_frontier_output['risks'], effcient_frontier_output['returns'])\n",
      "    ax.set_title('Efficient Frontier', fontsize=14)\n",
      "    ax.set_xlabel('Standard Deviation', fontsize=12)\n",
      "    ax.set_ylabel('Expected Return', fontsize=12)\n",
      "    ax.tick_params(labelsize=12)\n",
      "    plt.show()\n",
      "\n",
      "def get_minimum_variance_portfolio(return_table, allow_short=False, show_details=True):\n",
      "    \"\"\"\n",
      "    \u8ba1\u7b97\u6700\u5c0f\u65b9\u5dee\u7ec4\u5408\n",
      "    \n",
      "    Args:\n",
      "        return_table (DataFrame): \u6536\u76ca\u7387\u77e9\u9635\uff0c\u5217\u4e3a\u8d44\u4ea7\uff0c\u503c\u4e3a\u6309\u65e5\u671f\u5347\u5e8f\u6392\u5217\u7684\u6536\u76ca\u7387\n",
      "        allow_short (bool): \u662f\u5426\u5141\u8bb8\u5356\u7a7a\n",
      "        show_details (bool): \u662f\u5426\u663e\u793a\u7ec6\u8282\n",
      "\n",
      "    Returns:\n",
      "        dict: \u6700\u5c0f\u65b9\u5dee\u7ec4\u5408\u7684\u6743\u91cd\u4fe1\u606f\uff0c\u952e\u4e3a\u8d44\u4ea7\u540d\uff0c\u503c\u4e3a\u6743\u91cd\n",
      "    \"\"\"\n",
      "    \n",
      "    import numpy as np\n",
      "    from cvxopt import matrix, solvers\n",
      "    \n",
      "    assets = return_table.columns\n",
      "    n_asset = len(assets)\n",
      "    if n_asset < 2:\n",
      "        weights = np.array([1.])\n",
      "        weights_dict = {assets[0]: 1.}\n",
      "    else:\n",
      "        output = describe(return_table, is_print=False)\n",
      "        covariance_matrix = matrix(output['covariance_matrix'].as_matrix())\n",
      "        expected_return = output['annualized_return'].iloc[0, :].as_matrix()\n",
      "\n",
      "        P = 2 * covariance_matrix\n",
      "        q = matrix(np.zeros(n_asset))\n",
      "\n",
      "        if allow_short:\n",
      "            G = matrix(0., (n_asset, n_asset))\n",
      "        else:\n",
      "            G = matrix(np.diag(-1 * np.ones(n_asset)))\n",
      "        \n",
      "        h = matrix(0., (n_asset, 1))\n",
      "        A = matrix(np.ones(n_asset)).T\n",
      "        b = matrix([1.0])\n",
      "        solvers.options['show_progress'] = False\n",
      "        sol = solvers.qp(P, q, G, h, A, b)\n",
      "        weights = np.array(sol['x'].T)[0]\n",
      "        weights_dict = dict(zip(assets, weights))\n",
      "\n",
      "    r = np.dot(weights, output['annualized_return'].iloc[0, :].as_matrix())\n",
      "    v = np.sqrt(np.dot(np.dot(weights, covariance_matrix), weights.T))\n",
      "\n",
      "    if show_details:\n",
      "        print \"\"\"\n",
      "Minimum Variance Portfolio:\n",
      "    Short Allowed: {}\n",
      "    Portfolio Return: {}\n",
      "    Portfolio Volatility: {}\n",
      "    Portfolio Weights: {}\n",
      "\"\"\".format(allow_short, r, v, \"\\n\\t{}\".format(\"\\n\\t\".join(\"{}: {:.1%}\".format(k, v) for k, v in weights_dict.items()))).strip()\n",
      "    \n",
      "    return weights_dict\n",
      "\n",
      "def get_maximum_utility_portfolio(return_table, risk_aversion=3., allow_short=False, show_details=True):\n",
      "    \"\"\"\n",
      "    \u8ba1\u7b97\u6700\u5927\u6548\u7528\u7ec4\u5408\uff0c\u76ee\u6807\u51fd\u6570\u4e3a\uff1a\u671f\u671b\u5e74\u5316\u6536\u76ca\u7387 - \u98ce\u9669\u538c\u6076\u7cfb\u6570 * \u671f\u671b\u5e74\u5316\u65b9\u5dee\n",
      "    \n",
      "    Args:\n",
      "        return_table (DataFrame): \u6536\u76ca\u7387\u77e9\u9635\uff0c\u5217\u4e3a\u8d44\u4ea7\uff0c\u503c\u4e3a\u6309\u65e5\u671f\u5347\u5e8f\u6392\u5217\u7684\u6536\u76ca\u7387\n",
      "        risk_aversion (float): \u98ce\u9669\u538c\u6076\u7cfb\u6570\uff0c\u8d8a\u5927\u8868\u793a\u5bf9\u98ce\u9669\u8d8a\u538c\u6076\uff0c\u9ed8\u8ba4\u4e3a3.0\n",
      "        allow_short (bool): \u662f\u5426\u5141\u8bb8\u5356\u7a7a\n",
      "        show_details (bool): \u662f\u5426\u663e\u793a\u7ec6\u8282\n",
      "\n",
      "    Returns:\n",
      "        dict: \u6700\u5c0f\u65b9\u5dee\u7ec4\u5408\u7684\u6743\u91cd\u4fe1\u606f\uff0c\u952e\u4e3a\u8d44\u4ea7\u540d\uff0c\u503c\u4e3a\u6743\u91cd\n",
      "    \"\"\"\n",
      "    \n",
      "    import numpy as np\n",
      "    from cvxopt import matrix, solvers\n",
      "\n",
      "    assets = return_table.columns\n",
      "    n_asset = len(assets)\n",
      "    if n_asset < 2:\n",
      "        weights = np.array([1.])\n",
      "        weights_dict = {assets[0]: 1.}\n",
      "    else:\n",
      "        output = describe(return_table, is_print=False)\n",
      "        covariance_matrix = matrix(output['covariance_matrix'].as_matrix())\n",
      "        expected_return = output['annualized_return'].iloc[0, :].as_matrix()\n",
      "\n",
      "        if abs(risk_aversion) < 0.01:\n",
      "            max_ret = max(expected_return)\n",
      "            weights = np.array([1. if expected_return[i] == max_ret else 0. for i in range(n_asset)])\n",
      "            weights_dict = {asset: weights[i] for i, asset in enumerate(assets)}\n",
      "        else:\n",
      "            P = risk_aversion * covariance_matrix\n",
      "            q = matrix(-expected_return.T)\n",
      "\n",
      "            if allow_short:\n",
      "                G = matrix(0., (n_asset, n_asset))\n",
      "            else:\n",
      "                G = matrix(np.diag(-1 * np.ones(n_asset)))\n",
      "\n",
      "            h = matrix(0., (n_asset, 1))\n",
      "            A = matrix(np.ones(n_asset)).T\n",
      "            b = matrix([1.0])\n",
      "            solvers.options['show_progress'] = False\n",
      "            sol = solvers.qp(P, q, G, h, A, b)\n",
      "            weights = np.array(sol['x'].T)[0]\n",
      "            weights_dict = dict(zip(assets, weights))\n",
      "\n",
      "    r = np.dot(weights, output['annualized_return'].iloc[0, :].as_matrix())\n",
      "    v = np.sqrt(np.dot(np.dot(weights, covariance_matrix), weights.T))\n",
      "    \n",
      "    if show_details:\n",
      "        print \"\"\"\n",
      "Maximum Utility Portfolio:\n",
      "    Risk Aversion: {}\n",
      "    Short Allowed: {}\n",
      "    Portfolio Return: {}\n",
      "    Portfolio Volatility: {}\n",
      "    Portfolio Weights: {}\n",
      "\"\"\".format(risk_aversion, allow_short, r, v, \"\\n\\t{}\".format(\"\\n\\t\".join(\"{}: {:.1%}\".format(k, v) for k, v in weights_dict.items()))).strip()\n",
      "    \n",
      "    return weights_dict\n",
      "\n",
      "def get_maximum_sharpe_portfolio(return_table, riskfree_rate=0., allow_short=False, show_details=True):\n",
      "    \"\"\"\n",
      "    \u8ba1\u7b97\u6700\u5927\u6548\u7528\u7ec4\u5408\uff0c\u76ee\u6807\u51fd\u6570\u4e3a\uff1a\uff08\u671f\u671b\u5e74\u5316\u6536\u76ca\u7387 - \u65e0\u98ce\u9669\u6536\u76ca\u7387\uff09/ \u671f\u671b\u5e74\u5316\u65b9\u5dee\n",
      "    \n",
      "    Args:\n",
      "        return_table (DataFrame): \u6536\u76ca\u7387\u77e9\u9635\uff0c\u5217\u4e3a\u8d44\u4ea7\uff0c\u503c\u4e3a\u6309\u65e5\u671f\u5347\u5e8f\u6392\u5217\u7684\u6536\u76ca\u7387\n",
      "        riskfree_rate (float): \u65e0\u98ce\u9669\u6536\u76ca\u7387\n",
      "        allow_short (bool): \u662f\u5426\u5141\u8bb8\u5356\u7a7a\n",
      "        show_details (bool): \u662f\u5426\u663e\u793a\u7ec6\u8282\n",
      "\n",
      "    Returns:\n",
      "        dict: \u6700\u5c0f\u65b9\u5dee\u7ec4\u5408\u7684\u6743\u91cd\u4fe1\u606f\uff0c\u952e\u4e3a\u8d44\u4ea7\u540d\uff0c\u503c\u4e3a\u6743\u91cd\n",
      "    \"\"\"\n",
      "    \n",
      "    import numpy as np\n",
      "    from cvxopt import matrix, solvers\n",
      "\n",
      "    assets = return_table.columns\n",
      "    n_asset = len(assets)\n",
      "    if n_asset < 2:\n",
      "        output = describe(return_table, is_print=False)\n",
      "        r = output['annualized_return'].iat[0, 0]\n",
      "        v = output['annualized_volatility'].iat[0, 0]\n",
      "        weights_dict = {assets[0]: 1.}\n",
      "    else:\n",
      "        efs = get_efficient_frontier(return_table, allow_short=allow_short, n_samples=100)\n",
      "        i_star = max(range(100), key=lambda x: (efs.at[x, \"returns\"] - riskfree_rate) / efs.at[x, \"risks\"])\n",
      "        r = efs.at[i_star, \"returns\"]\n",
      "        v = efs.at[i_star, \"risks\"]\n",
      "        weights_dict = efs.at[i_star, \"weights\"]\n",
      "\n",
      "    s = (r - riskfree_rate) / v\n",
      "    \n",
      "    if show_details:\n",
      "        print \"\"\"\n",
      "Maximum Sharpe Portfolio:\n",
      "    Riskfree Rate: {}\n",
      "    Short Allowed: {}\n",
      "    Portfolio Return: {}\n",
      "    Portfolio Volatility: {}\n",
      "    Portfolio Sharpe: {}\n",
      "    Portfolio Weights: {}\n",
      "\"\"\".format(riskfree_rate, allow_short, r, v, s, \"\\n\\t{}\".format(\"\\n\\t\".join(\"{}: {:.1%}\".format(k, v) for k, v in weights_dict.items()))).strip()\n",
      "    \n",
      "    return weights_dict"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "markdown",
     "id": "BE9702475EEF4DE38A620D1ABA606C9B",
     "metadata": {},
     "source": [
      "\u4e0b\u9762\u7684\u4ee3\u7801\u5229\u7528\u4e0a\u8ff0\u7406\u8bba\u548c\u51fd\u6570\u6784\u9020\u4e86\u4e00\u4e2a\u7b80\u5355\u7684\u5747\u503c\u65b9\u5dee\u6a21\u578b\u793a\u4f8b\u3002"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "994F9C05E27D458CA50909246F4C7A3E",
     "input": [
      "start = '20130101'\n",
      "end = '20160630'\n",
      "indices = ['000300.ZICN', '000905.ZICN', '399006.ZICN', '000012.ZICN','000013.ZICN']\n",
      "df = DataAPI.MktIdxdGet(indexID=indices, beginDate=start, endDate=end, field=\"tradeDate,indexID,closeIndex\")\n",
      "df = df.pivot(index=\"tradeDate\", columns=\"indexID\", values=\"closeIndex\")\n",
      "for index in indices:\n",
      "    df[index] = df[index] / df[index].shift() - 1.\n",
      "return_table = df.dropna()\n",
      "\n",
      "describe(return_table, is_print=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": true,
     "id": "3477EC59481E4536A8E77DAFFDB7A96D",
     "input": [
      "efficient_frontier = get_efficient_frontier(return_table, allow_short=False, n_samples=50)\n",
      "efficient_frontier"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "9FF852F3C54D44C582D438BCEFDD1CA7",
     "input": [
      "draw_efficient_frontier(efficient_frontier)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "030772E033F441A6825E3AF5505F4411",
     "input": [
      "get_minimum_variance_portfolio(return_table, allow_short=False, show_details=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "8D82E5ECC23740BF8D09BFEE9B3D8F76",
     "input": [
      "get_maximum_utility_portfolio(return_table, risk_aversion=3, allow_short=False, show_details=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "id": "D5B883C081024A1D9DD299D6F2B7E522",
     "input": [
      "get_maximum_sharpe_portfolio(return_table, riskfree_rate=0.03, allow_short=True, show_details=True)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}